import {$diff} from "../static/js/diff"
import {$list_htmlToJson} from "../static/js/cnbeta_htmlToJson"
import {$mySetData} from "../static/js/mySetData"
import {$getOption} from "../static/js/wx_utils"


Page({

    data: {
        reqBaseURL: 'https://m.cnbeta.com',
        reqListURL: 'https://m.cnbeta.com/list/latest_%v.htm',
        loadingImg: "/static/img/loadingImg.gif",
        errImg: "/static/img/errimg.jpg",
        readDataLimit: 300, //保存到本地数据的限制,限制多少条数据,防止数据超过微信规定的10M缓存
        readData: [], //读取过的数据
        index: 1,
        enablePullDownRefresh: false,
        enableBootonRefresh: false,
        dataList1: [],
        setMyData: null,
        nav: null, //子组件
        envVersion: __wxConfig.envVersion,
        input: "",
        input_add: "",
    },

    inputAction(){
        let v = this.data.input_add + this.data.input;
        this.setData({input_add: v});
        this.setData({input: ""});
    },

    onRefresh() {
        this.setData({enablePullDownRefresh: true});
        this.requsetNews2();
    },

    //图片加载成功
    loadSuccess(e) {
        let i = e.currentTarget.dataset.i;
        let self = this;
        let v = {["dataList1[" + i + "].showImg"]: true};
        //self.setData();
        self.data.setMyData(v);
    },

    //图片加载失败
    loadError(e) {
        let i = e.currentTarget.dataset.i;
        let v = e.currentTarget.dataset.v;
        v.showImg = true;
        v.Img = this.data.errImg;
        this.setData({["dataList1[" + i + "]"]: v});
    },

    //处理请求成功后的数据
    handleSuccessData(self, index, dataList) {

        //如果是阅读过的新闻标识一下
        let readData = self.data.readData;
        lable: for (var k2 in dataList) {
            for (var k in readData) {
                var d = readData[k];
                var d2 = dataList[k2];
                if (d.Href == d2.Href) {
                    d2.isRead = true;
                    continue lable;
                }
            }
        }

        //上拉加载更多的逻辑
        if (index && index > 1) {
            dataList = self.data.dataList1.concat(dataList);
        }

        //显示加载图标
        for (var _k in dataList) {
            var v = dataList[_k];
            var v2 = self.data.dataList1[_k];
            if (v2 && v.Img == v2.Img && v2.showImg) {
                v.showImg = true;
                continue;
            } else {
                v.showImg = false;
            }
        }

        //渲染数据
        let diffVal2 = $diff({dataList1: dataList}, {dataList1: self.data.dataList1});
        this.setData(diffVal2, function () {
            self.data.index = index;
            self.hideLoad();
        });

    },

    // 读过的新闻写入本地存储
    readDataAction: function readDataAction(e) {
        let i = e.currentTarget.dataset.i;
        let v = e.currentTarget.dataset.v;

        //跳转到路由
        wx.navigateTo({
            url: '/page/page?affection=' + v.Href
        })

        if (v.isRead) return;
        this.setData({["dataList1[" + i + "].isRead"]: true});

        v.showImg = false;
        v.isRead = true;
        this.data.readData.unshift(v);
        var readData = this.data.readData;
        if (readData.length > this.readDataLimit) {
            readData.splice(this.readDataLimit - 1, readData.length - this.readDataLimit);
        }
        wx.setStorage({
            key: "readData",
            data: readData
        });
    },

    //获取读取过的数据
    getReadData: function getReadData() {
        var self = this;
        var readData = wx.getStorageSync("readData");
        readData = this.data.readData = readData || [];
        var dataList = [];

        //如果历史数据过多,那么只显示20条
        if (readData.length > 20) {
            var d = readData.slice(0, 20);
            dataList = JSON.parse(JSON.stringify(d));
        } else {
            dataList = JSON.parse(JSON.stringify(readData));
        }

        self.setData({dataList1: dataList});

    },

    // 请求新闻2
    requsetNews2(inputIndex) {
        const self = this;
        let index = inputIndex || 1;
        let url = this.data.reqListURL + "";
        url = url.replace("%v", index + "");
        //console.log("requsetNews.url", url)
        wx.request({
            url: url,
            success: function(res) {
                let dataList = $list_htmlToJson(res.data);
                self.handleSuccessData(self, index, dataList);
            },
            fail: function(res) {

                setTimeout(function () {
                    self.hideLoad();
                    wx.showModal({
                        title: '加载数据失败!',
                        content: '您的网络不太好, 请选择是否重试 ?',
                        showCancel: true,//是否显示取消按钮
                        cancelText: "否",//默认是“取消”
                        confirmText: "是",//默认是“确定”
                        success: function (res) {
                            if (res.cancel) return;//点击取消,默认隐藏弹框
                            wx.showLoading({title: '加载中...'});
                            self.requsetNews2(inputIndex);
                        }
                    });
                }, 1500)
            }
        });
    },

    hideLoad: function () {
        wx.hideLoading();
        wx.stopPullDownRefresh();
        this.setData({
            enableBootonRefresh: false,
            enablePullDownRefresh: false
        })
        //$stopWuxRefresher("#index-refresher", this);
    },

    //清除缓存
    cleanCache: function (v) {
        var version = wx.getStorageSync("version");
        if (!version || version != v) {
            wx.clearStorageSync();
            wx.setStorageSync("version", v);
        }
    },

    // 上拉加载更多
    onReachBottom: function () {
        //如果现在正在刷新,那么不能再次刷新
        const self = this;
        if (this.data.enableBootonRefresh) return;
        this.setData({enableBootonRefresh: true}, function () {
            this.requsetNews2(self.data.index + 1);
        })
    },

    // 下拉刷新触发方法
    onPullDownRefresh: function () {
        this.data.index = 1;
        this.setData({enablePullDownRefresh: true});
        this.requsetNews2();
    },


    //生命周期 - 加载小程序后
    onLoad: function () {
        wx.showLoading({title: '加载中...'});
        /*wx.showNavigationBarLoading();*/

        wx.showShareMenu();
        this.cleanCache(5);
    },

    //生命周期 - 页面渲染完成
    onReady: function () {

        var to = $getOption("to");
        if(to && to != "undefined"){
            wx.navigateTo({
                url: to + ("?affection=" + $getOption("affection"))
            })
        }

        //this.requsetNews2();
        this.data.setMyData = $mySetData(this);
    },

    //生命周期 - 页面显示
    onShow: function () {
        if (this.data.dataList1.length != 0) return;
        wx.showLoading({title: '加载中...'});
        this.getReadData();
        this.requsetNews2();
    },

    //分享的内容
    onShareAppMessage: function onShareAppMessage(res) {
        return {
            path: "/index/index",
            title: "邀您一起阅读: 无推荐, 无广告的纯粹新闻体验"
        };
    },

    //生命周期 - 小程序卸载
    onUnload: function onUnload() {

    }
});

